<template>
  <div>
    <div>
      <el-form :inline="true" :model="param">
        <el-col :span="6">
          <el-form-item label="茶室名">
            <el-input @clear="findHouse" v-model="param.name" placeholder="筛选名称" clearable prefix-icon="el-icon-search"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item>
            <el-button type="primary" @click="findHouse">查询</el-button>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item>
            <el-button type="success" @click="toAdd">新增</el-button>
          </el-form-item>
        </el-col>
      </el-form>
    </div>
    <div style="margin-bottom: 10px ;">

      <el-table ref="userTable" :data="tableData" :stripe="true" :border="true"
                style="width: 100%">
        <el-table-column prop="name" label="茶室名" width="100"></el-table-column>
        <el-table-column prop="img" label="图片" width="120" align="center">
          <template v-slot="{row}">
            <el-image :src='"/api/fileserver/" +row.img' style=" height: 50px;"
                      :preview-src-list="['/api/fileserver/' +row.img]"></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="茶室规格" width="100" align="center">
          <template v-slot="{row}">
            <el-tag effect="plain" v-if="row.type === '小'" size="small">小</el-tag>
            <el-tag effect="plain" type="warning" v-if="row.type === '中'" size="medium">中</el-tag>
            <el-tag effect="plain" type="success" v-if="row.type === '大'">大</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="价格" width="90" align="center">
          <template v-slot="{row}">
            <h4  >{{ row.price }} 元</h4>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="155"></el-table-column>
        <el-table-column prop="seat" label="茶室号" width="80" align="center"></el-table-column>
        <el-table-column prop="branchName" label="所属店铺">
          <template v-slot="{row}">
            <span> {{row.address }}，{{ row.branchName }} </span>
          </template>
        </el-table-column>
        <el-table-column prop="isUse" label="茶室状态" width="100" align="center">
          <template v-slot="{row}">
            <el-tag type="success" v-if="row.isUse === 1" size="small">空房</el-tag>
            <el-tag effect="dark" type="danger" v-if="row.isUse === 2" size="small">预定</el-tag>
            <el-tag v-if="row.isUse === 3" type="danger" size="small">报修</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="useTime" label="预定时间" width="160" align="center"></el-table-column>
        <el-table-column label="操作" width="120">
          <template v-slot="{row}">
            <el-button @click="dingHouse(row)" :disabled="row.isUse === 2 || row.isUse === 3 " type="text" size="small">预定</el-button>
            <el-button @click="wuHouse(row)" :disabled="row.isUse === 1 || row.isUse === 3" type="text" size="small">启用</el-button>
            <el-button @click="delHouse(row)" type="text" size="small">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination background :page-sizes="[8, 16, 30]" @current-change="pageChange($event)"
                     :page-size=this.param.size @size-change="sizeChange($event)"
                     layout="total,prev,pager,next,sizes" :total="total" small>
      </el-pagination>

      <!--新增-->
      <el-dialog title="新增茶室" :visible.sync="isAdding" width="40%" :close-on-click-modal="false" center>
        <el-form :model="addForm" :rules="rules" ref="addForm" label-width="100px">
          <el-form-item label="茶室名称" prop="name">
            <el-input v-model="addForm.name" placeholder="请输茶室名称"></el-input>
          </el-form-item>
          <el-form-item label="所属分店" prop="branchId">
            <el-select v-model="addForm.branchId" placeholder="请选择分店" clearable style="width: 100%">
              <el-option v-for="item in branchList" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="茶室照片" prop="file">
            <el-upload ref="file" action="#" list-type="picture-card" :auto-upload="false" :limit="1" :on-remove="handleRemove"
                       :file-list="file" :before-upload="beforeAvatarUpload" :on-change="upFile" :class="{disabled:uploadDisabled }">
              <i slot="default" class="el-icon-plus"></i>
              <div slot="file" slot-scope="{file}">
                <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
                <span class="el-upload-list__item-actions">
                      <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                        <i class="el-icon-zoom-in"></i>
                       </span>
                       <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)">
                         <i class="el-icon-delete"></i>
                       </span>
                  </span>
              </div>
            </el-upload>
          </el-form-item>
          <el-form-item label="茶室价格" prop="price">
            <el-input v-model="addForm.price" placeholder="请输价格">
              <template slot="append" >元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="茶室编号" prop="seat">
            <el-input v-model="addForm.seat" placeholder="请输茶室在茶楼编号"></el-input>
          </el-form-item>
          <el-form-item label="茶室规格" prop="type">
            <el-input v-model="addForm.type" placeholder="请输大、中、小"></el-input>
          </el-form-item>
          <el-form-item label="茶室茶具" prop="teaSet">
            <el-input v-model="addForm.teaSet" placeholder="请输茶具数量">
              <template slot="append" >件</template>
            </el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
        <el-button @click="resetForm('addForm')">重置</el-button>
        <el-button type="primary" @click="addHouse('addForm')">确认</el-button>
      </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
export default {
  name: "TeaHouse",
  data() {
    let checkNum = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('价格不能为空'));
      }
      setTimeout(() => {
        if (!(/^[+]?(\d+)$|^[+]?(\d+\.\d+)$/).test(value)) {
          callback(new Error('请输入数字值'))
        } else {
          callback()
        }
      }, 1000);
    };
    return {
      userInfo: [],
      tableData: [],
      total: 0,
      isAdding: false,
      addForm:{
        teaSet:'',
        branchId:''
      },
      branchList:{},
      file:[],
      uploadDisabled :'',
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      param:{
        name: '',
        page: 1,
        size: 8,
      },
      house:{

      },
      priceDate:{
        house:'',
        price: '',
        createUserName:'',
        remark:'',
      },
      rules:{
        name: [
          {required: true, message: '请输入该选项', trigger: 'blur'},
          {min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur'}
        ],
        type: [
          {required: true, message: '请输入该选项', trigger: 'blur'},
          {min: 1, max: 1, message: '请输入’大‘ ’中‘ ‘小’其一', trigger: 'blur'}
        ],
        price: [
          {required: true, validator: checkNum, trigger: 'blur'},
        ],
        seat: [
          {required: true, message: '请输入该选项', trigger: 'blur'},
        ],
        teaSet: [
          {required: true, message: '请输入该选项', trigger: 'blur'},
        ],
        branchId: [
          {required: true, message: '请选择该选项', trigger: 'blur'},
        ],
      },
    }
  },
  mounted() {
    this.findHouse()
    this.findBranch()
    this.userInfo = JSON.parse(sessionStorage.getItem("userInfo"))
  },
  methods:{
    findHouse() {
      this.$axios.get('/api/house/findHouse', {params: this.param}).then(res => {
        this.tableData = res.data.data.list;
        this.total = res.data.data.total;
      }).catch(e => console.log(e))
    },
    findBranch(){
      this.$axios.get('/api/house/findBranch', {params: this.param}).then(res => {
        this.branchList = res.data.data.list;
        console.log(this.branchList)
      }).catch(e => console.log(e))
    },
    toAdd(){
      this.isAdding = true
    },
    addHouse(addForm){
      this.$refs[addForm].validate((valid) => {
        if (valid){
          let formData = new FormData()
          //将图片加入FormData()
          formData.append('file',this.file[0].raw)
          //将addInfo里面的数据循环加入FormData()
          for (let key of Object.keys(this.addForm)){
            formData.append(key,this.addForm[key])
          }
          //FormData是一种特殊类型的对象，它不可字符串化，不能仅使用console.log打印出来
          formData.forEach((value, key) => {
            console.log("key %s: value %s", key, value);
          })
          this.$axios.post('/api/house/addHouse',formData,{
            headers:{'Content-Type': 'multipart/form-data;charset=utf-8'}
          }).then(res =>{
            if (res.data.status ===1){
              this.$notify({
                title: '提示',
                message: '新增成功',
                type: 'success'
              })
              this.resetForm('addForm')
              this.isAdding = false
              this.findHouse()
            }else {
              this.$notify({
                title: '提示',
                message: res.data.message,
                type: 'error'
              });
            }
          })
        }
      })
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    upFile(file, fileList) {
      //判断上传1后禁止上传
      this.uploadDisabled  = fileList.length >= 1;
      //获取当前文件数据解析供食用
      this.$forceUpdate();
      this.file.splice(0, this.file.length - 1);
      let url = window.URL.createObjectURL(new Blob([file.raw]));
      this.file = [{
        url: url,
        raw: file.raw,
        name: file.name,
      }]
      console.log(this.file)
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isPNG = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG && !isPNG) {
        this.$message.error('上传图片只能是 JPG/PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    handleRemove(file) {
      // 删除
      if (this.file.indexOf(this.file + file.url)) {
        this.file.splice(this.file.indexOf(this.file + file.url), 1);
      }
      for (let key in file) {
        delete file[key];
      }
      //删除后回显上传框(此时file已经被清空)
      this.uploadDisabled = false
    },
    dingHouse(row) {
      this.house.id = row.id
      this.house.isUse = 2 //预定房
      const today = new Date((new Date).getTime() + 8*60*60*1000);
      this.house.useTime = today.toJSON().split('T').join(' ').substring(0,19); // 将1970/08/08转化成1970-08-08
      console.log(this.house)
      this.upApi()
      this.priceDate.createUserName = this.userInfo.name
      this.priceDate.price = row.price
      this.priceDate.remark = '租用:'+ row.name + '3小时'
      this.priceDate.house = row.name
      this.$axios.post('/api/house/add', this.priceDate).then(res => {
        if (res.data.status === 1) {
          this.$notify({
            title: '提示',
            message: '资金入账成功',
            type: 'success'
          });
          this.findHouse()
        }
      })
    },
    wuHouse(row) {
      this.house.id = row.id
      this.house.isUse = 1  //空茶室
      this.house.useTime = null
      this.upApi()
    },
    upApi(){
      this.$axios.post('/api/house/upHouse', this.house).then(res => {
        if (res.data.status === 1) {
          this.$notify({
            title: '提示',
            message: '操作成功',
            type: 'success'
          });
          this.findHouse()
        } else {
          this.$notify({
            title: '提示',
            message: res.data.message,
            type: 'error'
          });
        }
      })
    },
    delHouse(row){
      this.$confirm('将要删除该茶室, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log(row)
        if ( row.isUse !== 2 ) {
          let ids = row.id
          return this.$axios.delete(`/api/house/delHouse?ids=${ids}`).then(res => {  //物理删除
            if (res.data.status === 1) {  //删除成功
              this.$notify({
                title: '提示',
                message: '删除成功',
                type: 'success'
              });
              this.findHouse();
            } else {
              this.$notify({
                title: '提示',
                message: res.data.message,
                type: 'error'
              });
            }
          }).catch(e => e);
        } else {
          this.$notify({
            title: '提示',
            message: '该茶室已被预定使用,暂时无法删除',
            type: 'error'
          });
        }
      })
    },
    resetForm(addForm) {
      this.$nextTick(()=>{
        this.handleRemove(addForm)
        this.$refs[addForm].resetFields();
      })
    },
    pageChange(page) {
      this.param.page = page;
      this.findHouse()
    },
    sizeChange(size) {
      this.param.size = size;
      this.findHouse()
    },
  }

}
</script>

<style scoped>

</style>
